﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleScale.DataAccess;
using VehicleScale.Models;

namespace VehicleScale.Forms.Files
{
    public partial class FrmProducts : TemplateForm
    {
        #region Ctors
        private FrmProducts()
        {
            InitializeComponent();

            Initialize();

            this.panel1.BackColor = Setting.BackColor;
            this.uiGroupBox1.BackColor = Setting.BackColor;
            this.Size = new Common().SizeList;
        }
        #endregion

        #region Singleton Members
        private static volatile FrmProducts instance;
        private static object syncRoot = new Object();

        public static FrmProducts Instance
        {
            get
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new FrmProducts();
                }

                return instance;
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            instance = null;
            base.OnClosed(e);
        }
        #endregion

        #region Field Members
        IProductDataAccess _dataAccess = new ProductDataAccess();
        IList<ProductModel> _productList;
        IList<CategoryModel> _categories;
        #endregion

        #region Method Members

        /// <summary>
        /// Initialize methods of the application
        /// </summary>
        private void Initialize()
        {
            // Set Events
            this.btnReset.Click += new EventHandler(delegate { ClickButtonReset(); });
            this.btnSearch.Click += new EventHandler(delegate { ClickButtonSearch(); });
            this.btnNew.Click += new EventHandler(delegate { ClickButtonNew(); });
            this.btnEdit.Click += new EventHandler(delegate { ClickButtonEdit(); });
            this.btnDelete.Click += new EventHandler(delegate { ClickButtonDelete(); });
            this.btnExcel.Click += new EventHandler(delegate { base.OnExportExcel(this.gridEX1); });
            this.btnClose.Click += new EventHandler(delegate { instance = null; this.Close(); });
            this.gridEX1.DoubleClick += new EventHandler(delegate { ClickButtonEdit(); });

            LoadCategoriesToCombo();

            // Get all products
            this.ClickButtonReset();
            try
            {
                LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Mo Form San pham");
            }
            catch
            {
            }
            // Set permission
            //bool IsAdmin = (Common.UserLogin.GroupPermissionID == 1);
            //this.btnDelete.Visible = IsAdmin;
            //this.btnEdit.Visible = IsAdmin;
        }

        private void LoadCategoriesToCombo()
        {
            ICategoryDataAccess dataAccess = new CategoryDataAccess();
            _categories = dataAccess.GetAll();
            this.cboCategoryID.DataSource = _categories;
            this.cboCategoryID.ValueMember = "CategoryID";
            this.cboCategoryID.DisplayMember = "CategoryName";
        }

        #endregion

        #region Action Members

        /// <summary>
        /// Click button search
        /// </summary>
        private void ClickButtonSearch()
        {
            _dataAccess.SearchObject = new ProductModel();
            _dataAccess.SearchObject.ProductID = this.edtProductID.Text;
            _dataAccess.SearchObject.ProductName = this.edtProductName.Text;
            _dataAccess.SearchObject.Unit = this.edtUnit.Text;
            if (this.cboCategoryID.Value != null)
                _dataAccess.SearchObject.CategoryID = this.cboCategoryID.Value.ToString();

            _productList = _dataAccess.Searcher();

            if (_productList == null || _productList.Count == 0)
                this.gridEX1.BuiltInTexts[Janus.Windows.GridEX.GridEXBuiltInText.GroupByBoxInfo] = "Không tìm thấy thông tin."; // Bạn phải nhập ít nhất 1 tiêu chí tìm kiếm.";
            else
                this.gridEX1.BuiltInTexts[Janus.Windows.GridEX.GridEXBuiltInText.GroupByBoxInfo] = "Chọn cột cần group.";

            this.gridEX1.DataSource = _productList;
        }

        /// <summary>
        /// Click button reset
        /// </summary>
        private void ClickButtonReset()
        {
            this.edtProductID.Text = String.Empty;
            this.edtProductName.Text = String.Empty;
            this.edtUnit.Text = String.Empty;
            this.cboCategoryID.SelectedIndex = -1;

            this.ClickButtonSearch();

            this.edtProductID.Focus();
        }

        /// <summary>
        /// Click button new
        /// </summary>
        private void ClickButtonNew()
        {
            int count = _productList.Count;
            // Show the updating staff instance
            FrmUpdateProducts instance = new FrmUpdateProducts();
            instance.Categories = _categories;
            instance.Collection = _productList;
            instance.ShowDialog();

            if (count < _productList.Count)
            {
                // Refresh data
                this.gridEX1.Refetch();
            }
        }

        /// <summary>
        /// Click button edit
        /// </summary>
        private void ClickButtonEdit()
        {
            if (this.gridEX1.CurrentRow == null)
            {
                Library.Tools.MsgBox.Show(Messages.EditMessage, Messages.NoticeTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Edit employee information
            FrmUpdateProducts instance = new FrmUpdateProducts();
            instance.Categories = _categories;
            instance.Product = this.gridEX1.CurrentRow.DataRow as ProductModel;
            DialogResult result = instance.ShowDialog();
            if (result == DialogResult.OK)
            {
                // Refresh data
                this.gridEX1.Refetch();
            }
        }

        /// <summary>
        /// Click button delete
        /// </summary>
        private void ClickButtonDelete()
        {
            if (this.gridEX1.CurrentRow == null)
            {
                Library.Tools.MsgBox.Show(Messages.DeleteMessage, Messages.NoticeTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            ProductModel product = this.gridEX1.CurrentRow.DataRow as ProductModel;
            DialogResult result = Library.Tools.MsgBox.Show(Messages.ConfirmDeleteMessage, Messages.QuestionTitle, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                string productID = product.ProductID;
                bool r = _dataAccess.Delete(product);

                if (r)
                {
                    this.gridEX1.CurrentRow.Delete();

                    var query = (from c in Common.Products
                                 where c.ProductID == productID
                                 select c).SingleOrDefault();
                    if (query != null)
                    {
                        Common.Products.Remove(query);
                    }
                    try
                    {
                        LogFile.WriteLog(LogFile.nameFile, LogFile.userLogin, "Xoa san pham : " + product.ProductName);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    Library.Tools.MsgBox.Show(String.Format(Messages.DeleteFailedMessage, "sản phẩm"),
                            "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion

    }
}
